package com.moorror.cola.strategy.plugin.markers;

import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.navigation.NavigationGutterIconRenderer;
import com.intellij.navigation.GotoRelatedItem;
import com.intellij.openapi.util.NotNullFactory;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.psi.PsiElement;
import com.intellij.psi.SmartPointerManager;
import com.intellij.psi.SmartPsiElementPointer;
import com.moorror.cola.strategy.plugin.bean.PsiElementWrapper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author jiyanghuang
 * @Date 2022/3/14 11:03 PM
 */
public class ColaNavigationGutterIconRenderer extends NavigationGutterIconRenderer {

    private Icon icon;
    private String popupTitle;
    private String tooltipText;
    private String emptyText;
    private NotNullLazyValue<List<PsiElementWrapper>> elements;

    public ColaNavigationGutterIconRenderer(Icon icon, String popupTitle, String tooltipText, String emptyText, NotNullLazyValue<List<PsiElementWrapper>> elements) {
        super(popupTitle, emptyText, () -> {
            return new ColaCellRenderer(elements);
        }, NotNullLazyValue.createValue(new NotNullFactory<List<SmartPsiElementPointer<?>>>() {
            @Override
            public @NotNull
            List<SmartPsiElementPointer<?>> create() {
                return elements.getValue().stream().map(p -> {
                    SmartPointerManager smp = SmartPointerManager.getInstance(p.getElement().getProject());
                    SmartPsiElementPointer<PsiElement> sp = smp.createSmartPsiElementPointer(p.getElement());
                    return sp;
                }).collect(Collectors.toList());
            }
        }));

        this.icon = icon;
        this.popupTitle = popupTitle;
        this.tooltipText = tooltipText;
        this.elements = elements;
    }

    @Override
    public @NotNull Icon getIcon() {
        return icon;
    }

    @Override
    public @NotNull Alignment getAlignment() {
        return Alignment.LEFT;
    }

    @Nullable
    @Override
    public String getTooltipText() {
        return tooltipText;
    }

    public LineMarkerInfo<?> createLineMarkerInfo(PsiElement element){
        return new RelatedItemLineMarkerInfo(
                element,
                element.getTextRange(),
                icon,
                (t) -> tooltipText,
                this,
                getAlignment(),
                () -> { return elements.getValue().stream().map(e -> new GotoRelatedItem(e.getElement())).collect(Collectors.toList());}
        );
    }
}
